package com.gitee.wsl.serialization.time

import kotlinx.datetime.LocalDateTime
import kotlinx.serialization.KSerializer
import kotlinx.serialization.Serializable
import kotlinx.serialization.descriptors.PrimitiveKind
import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.encoding.Encoder

object Iso8601DateSerializer : KSerializer<LocalDateTime> {
    override val descriptor = PrimitiveSerialDescriptor("Iso8601LocalDateTime", PrimitiveKind.STRING)

    override fun deserialize(decoder: Decoder)
        = LocalDateTime.parse(decoder.decodeString().removeSuffix("Z"))

    override fun serialize(encoder: Encoder, value: LocalDateTime)
        = encoder.encodeString(value.toString())
}

typealias SerializableIso8601Date = @Serializable(with = Iso8601DateSerializer::class) LocalDateTime